Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Networking → URL Class

Networking

URL Class

The `java.net.URL` class represents a Uniform Resource Locator (URL). A URL specifies the location of a resource on the internet, such as a webpage, image, or file. The `URL` class provides methods for parsing and manipulating URLs, and for opening connections to the resources they identify.

Key Components of a URL:

A URL typically consists of several components protocol: The method used to access the resource (e.g., `http`, `https`, `ftp`, `file`). authority: The server hosting the resource. This usually includes the hostname (e.g., `www.example.com`) and optionally a port number (e.g., `:8080`). path: The specific location of the resource on the server (e.g., `/index.html`, `/images/logo.png`). query: Parameters passed to the resource (e.g., `?name=John&age=30`). fragment: A part of the resource to be displayed (e.g., `#section1`).

Creating a URL Object:

You create a `URL` object by passing a URL string to the constructor
Java URL Object example import java.net.URL; import java.net.MalformedURLException; import java.io.IOException; public class URLExample { public static void main(String[] args) { try { // Create a URL object URL url1 = new URL("https://www.example.com/index.html"); System.out.println("URL: " + url1); // Create a URL with a query parameter URL url2 = new URL("http://www.example.com/search?q=java"); System.out.println("URL: " + url2); // Create a URL with a fragment identifier URL url3 = new URL("https://docs.oracle.com/javase/8/docs/api/java/net/URL.html#getRef()"); System.out.println("URL: " + url3); // Create a file URL URL url4 = new URL("file:///path/to/my/file.txt"); //Note the three slashes for file URLs. System.out.println("URL: " + url4); } catch (MalformedURLException e) { System.err.println("Invalid URL: " + e.getMessage()); } } }

Accessing URL Components

The `URL` class provides methods to access individual components of the URL
Accessing URL Components import java.net.URL; import java.net.MalformedURLException; public class URLComponentExample { public static void main(String[] args) { try { URL url = new URL("https://username:password@www.example.com:8080/path/to/resource?param1=value1¶m2=value2#fragment"); System.out.println("Protocol: " + url.getProtocol()); System.out.println("Authority: " + url.getAuthority()); System.out.println("Host: " + url.getHost()); System.out.println("Port: " + url.getPort()); // Returns -1 if no port specified System.out.println("Path: " + url.getPath()); System.out.println("Query: " + url.getQuery()); System.out.println("Ref (Fragment): " + url.getRef()); System.out.println("User Info: " + url.getUserInfo()); // username:password in this case. } catch (MalformedURLException e) { System.err.println("Invalid URL: " + e.getMessage()); } } }

Opening a Connection

The `openConnection()` method returns a `URLConnection` object, which allows you to interact with the resource at the URL. This often involves making HTTP requests (GET, POST, etc.).
Opening a Connection import java.net.URL; import java.net.URLConnection; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; public class URLConnectionExample { public static void main(String[] args) { try { URL url = new URL("https://www.example.com"); //Replace with a valid URL URLConnection connection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } catch (IOException e) { System.err.println("Error opening connection: " + e.getMessage()); } } }

Important Considerations:

Error Handling: Always use `try-catch` blocks to handle potential `MalformedURLException` (for invalid URLs) and `IOException` (for network errors). Security: Be cautious when handling URLs from untrusted sources. Avoid directly executing code from URLs. Network Access: Ensure your application has the necessary network permissions.

Tutorials